function y=ditch(x,w)
%% Detect the ditches in an image


%% const
if nargin < 2
    w = 32;
end

%% program

y = zeros(size(x));
for i = 1 : length(x)
    m = x(i);
    lefti = max(1, i-w);
    righti = min(length(x), i+w);
    m = mean(x(lefti:righti));
   
    leftn = 0;
    lefthi = m;%%x(i);
    leftnt = 0;
    for j = i-1 : -1: lefti
        if x(j) > lefthi
            lefthi = x(j);
            leftnt = 1;
        elseif leftnt==1
            nd = (lefthi+x(i))/2;
            if (x(j) < nd)
                leftn = 1;
                break;
            end
        end
    end

    rightn = 0;
    righthi = m;%%x(i);
    rightnt = 0;
    for j = i+1 : righti
        if x(j) > righthi
            righthi = x(j);
            rightnt = 1;
        elseif rightnt == 1
            nd = (righthi+x(i))/2;
            if (x(j) < nd)
                rightn = 1;
                break;
            end
        end
    end
    
    skip = (leftn==1 && rightn==1);

    if m > x(i) && ~skip
        y(i) = (m - x(i)) / m;
    end
end

%figure; plot(y);
z = peak(y);
z(1:w) = 0;
z(end-w+1:end) = 0;
y = z;
%figure; stem(y);
